package com.augmentum.login.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.augmentum.login.AppContent;
import com.augmentum.login.Constants;
import com.augmentum.login.exception.ParamException;
import com.augmentum.login.exception.ServiceException;
import com.augmentum.login.model.Page;
import com.augmentum.login.model.Question;
import com.augmentum.login.service.QuestionService;
import com.augmentum.login.util.PathUtil;
import com.augmentum.login.util.Prop;
import com.augmentum.login.util.Regular;
import com.augmentum.login.util.StringUtil;

@Controller("questionController")
@RequestMapping("/page/question")
public class QuestionController extends BaseController {
    private final Logger logger = Logger.getLogger(QuestionController.class);
    @Resource
    private QuestionService questionService;
    @RequestMapping("/create")
    public ModelAndView create(@RequestParam(value = "questionId") String questionId,
            @RequestParam(value = "description") String description, @RequestParam(value = "optionA") String optionA,
            @RequestParam(value = "optionB") String optionB, @RequestParam(value = "optionC") String optionC,
            @RequestParam(value = "optionD") String optionD, @RequestParam(value = "answer") String answer) {
        ModelAndView modelView = new ModelAndView();
        HttpSession session = (HttpSession)AppContent.getAppContent().getSession();
        try {
            Question question = new Question();
            question.setQuestionId(questionId);
            question.setDescription(description);
            question.setOptionA(optionA);
            question.setOptionB(optionB);
            question.setOptionC(optionC);
            question.setOptionD(optionD);
            question.setAnswer(answer);

            questionService.addQuestion(question);
            modelView.setView(new RedirectView(PathUtil.getFullPath(Constants.SEARCH_QUESTION_SERVLET)));
            return modelView;
        } catch (ParamException paremException) {
            logger.warn(paremException.getMessage());
            modelView.setView(new RedirectView(PathUtil.getFullPath(Constants.CREATE_PAGE)));
            session.setAttribute(Constants.QUESTION_PARAM_MSG, paremException.getExceptionFields());
            return modelView;
        } catch (ServiceException serviceException) {
            logger.warn(serviceException.getMessage());
            modelView.setView(new RedirectView(PathUtil.getFullPath(Constants.CREATE_PAGE)));
            session.setAttribute(Constants.QUESTION_SERVICE_MSG, serviceException.getMessage());
            return modelView;
        }
    }

    @RequestMapping("/delete")
    public ModelAndView delete(@RequestParam(value = "questionStr") String questionStr) {
        ModelAndView modelView = new ModelAndView();
        questionService.removeBathcQuestions(questionStr, ",");
        modelView.setView(new RedirectView(PathUtil.getFullPath(Constants.SEARCH_QUESTION_SERVLET)));
        return modelView;
    }

    @RequestMapping("/search")
    public ModelAndView search(@RequestParam(value = Constants.DESCRIPTION, defaultValue = "") String description,
            @RequestParam(value = Constants.ORDER, defaultValue = "") String order,
            @RequestParam(value = Constants.CURRENTPAGE, defaultValue = "") String currentPage,
            @RequestParam(value = Constants.PAGE_SIEZ, defaultValue = "") String pageSize) {
        ModelAndView modelView = new ModelAndView();
        Page page = new Page();
        if (StringUtil.isEmpty(description)) {
            description = "";
        } else {
            description = StringUtil.replaceSpecialChars(description);
        }
        if (StringUtil.isEmpty(order)) {
            order = "";
        } else if (!order.matches(Regular.ORDER.getValue())) {
            order = "";
        }

        int totalCount = questionService.getQuestionCount(description);
        if (totalCount <= 0) {
            page.setTotalCount(1);
            page.setCurrentPage(1);
            page.setPageSize(Integer.parseInt(Prop.get(Constants.PAGE_SIEZ)));
            modelView.addObject(Constants.PAGE, page);
            modelView.addObject(Constants.QUESTION_LIST, new ArrayList<Question>());
            modelView.setViewName(Constants.LIST_QUESTION_JSP);
            return modelView;
        }
        if (StringUtil.isEmpty(currentPage)) {
            currentPage = "1";
        }

        if (!currentPage.matches(Regular.DIGIT.getValue())) {
            currentPage = "1";
        }

        if (StringUtil.isEmpty(pageSize) || !pageSize.matches(Regular.NUMBER.getValue())) {
            pageSize = Prop.get(Constants.PAGE_SIEZ); // set default value
        }

        page.setPageSize(Integer.parseInt(pageSize));
        page.setTotalCount(totalCount);
        int pageNum = Integer.parseInt(currentPage);
        if (pageNum < 1) {
            pageNum = 1;
        } else if (pageNum > page.getPageCount()) {
            pageNum = page.getPageCount();
        }
        page.setCurrentPage(pageNum);
        List<Question> list = questionService.searchQuestionsByPage(description, order, page);
        modelView.addObject(Constants.DESCRIPTION, description);
        modelView.addObject(Constants.ORDER, order);
        modelView.addObject(Constants.PAGE, page);
        
        modelView.addObject(Constants.QUESTION_LIST, list);
        modelView.setViewName(Constants.LIST_QUESTION_JSP);
        return modelView;
    }

    @RequestMapping("/edit")
    public ModelAndView edit(@RequestParam(value = "questionId") String questionId,
            @RequestParam(value = "description") String description, @RequestParam(value = "optionA") String optionA,
            @RequestParam(value = "optionB") String optionB, @RequestParam(value = "optionC") String optionC,
            @RequestParam(value = "optionD") String optionD, @RequestParam(value = "answer") String answer) {
        ModelAndView modelView = new ModelAndView();

        Question question = new Question();
        question.setQuestionId(questionId);
        question.setAnswer(answer);
        question.setDescription(description);
        question.setOptionA(optionA);
        question.setOptionB(optionB);
        question.setOptionC(optionC);
        question.setOptionD(optionD);
        try {
            questionService.modifyQuestion(question);
            modelView.setView(new RedirectView(PathUtil.getFullPath(Constants.SEARCH_QUESTION_SERVLET)));
            return modelView;
        } catch (ParamException paramException) {
            logger.warn(paramException.getMessage());
            modelView.setViewName(Constants.EDIT_QUESTION_JSP);
            modelView.addObject(Constants.QUESTION, question);
            modelView.addObject(Constants.QUESTION_PARAM_MSG, paramException.getExceptionFields());
            return modelView;
        }
    }

    @RequestMapping("/searchPage")
    public ModelAndView searchPage() {
        ModelAndView modelView = new ModelAndView();
        modelView.setViewName(Constants.LIST_QUESTION_JSP);
        return modelView;
    }

    @RequestMapping("/createPage")
    public ModelAndView createPage() {
        ModelAndView modelView = new ModelAndView();
        modelView.setViewName(Constants.CREATE_QUESTION_JSP);
        return modelView;
    }

    @RequestMapping("/editPage")
    public ModelAndView editPage(@RequestParam(value = "id") String id) {
        ModelAndView modelView = new ModelAndView();

        if (StringUtil.isEmpty(id)) {
            modelView.setView(new RedirectView(PathUtil.getFullPath(Constants.SEARCH_QUESTION_SERVLET)));
            return modelView;
        }

        Question question = questionService.getQuestion(id);
        if (question == null) {
            modelView.setView(new RedirectView(PathUtil.getFullPath(Constants.SEARCH_QUESTION_SERVLET)));
            return modelView;
        }
        modelView.addObject(Constants.QUESTION, question);
        modelView.setViewName(Constants.EDIT_QUESTION_JSP);
        return modelView;
    }
}
